package com.snopy.leetcode.index1_1000.index401_500;

/**
 * @author snopy
 * @version 1.0.0
 * @classname Question498
 * @description 对角线遍历 middle
 *给你一个大小为 m x n 的矩阵 mat ，请以对角线遍历的顺序，用一个数组返回这个矩阵中的所有元素。
 *
 * @email 77912204@qq.com
 * @date 2022/04/13 23:45
 */
public class Question498 {
    public static void main(String[] args) {
        int[][] nums = new int[][]{{1 ,2 ,3 ,4 ,5},
                                   {6 ,7 ,8 ,9 ,10},
                                   {11,12,13,14,15},
                                   {16,17,18,19,20}};
        int[] ints = new Question498().findDiagonalOrder(nums);
        for (int i = 0; i < ints.length; i++) {
            System.out.print(ints[i]+"\t");
        }
    }
    /**
     * @Description  对角线遍历
     * 横纵下标之和即为遍历的层数
     * @param mat:
     * @return: int[]
     * @Date 2022-04-20
     * @Author txl77912204@gmail.com
     **/
    public int[] findDiagonalOrder(int[][] mat) {

        int row = 0,col=0, m = mat.length,n = mat[0].length,k=0;
        int layer = m+n-1;
        int[] nums = new int[m*n];

        for (int l=0;l < layer;l++){
            if (l%2!=0){
                row = l < n ? 0:l-n+1;
                col = l < n ? l:n-1;
                while (row < m && col >-1){
                    nums[k++] = mat[row][col];
                    row++;
                    col--;
                }
            }else {
                row = l < m ? l:m-1;
                col = l < m ? 0:l-m+1;
                while (row > -1 && col < n){
                    nums[k++] = mat[row][col];
                    row--;
                    col++;
                }
            }

        }
        return nums;
    }
}
